// src/api.js
import axios from 'axios';
import router from '../main';
import Swal from 'sweetalert2';

const BASE_URL = "http://javaweb.rwklyd.icu:8082"; // 上线路径
// const BASE_URL = "http://localhost:8082"; // 测试路径

// 创建 axios 实例
const apiClient = axios.create({
    baseURL: BASE_URL,
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 请求拦截器
apiClient.interceptors.request.use(
    (config) => {
        // 从本地存储中获取 JWT 令牌
        const token = localStorage.getItem('token');

        // 检查 URL 是否包含 '/login'、'/register' 或 '/captcha'
        const isPublicRequest = config.url.includes("/login") || config.url.includes("/register") || config.url.includes("/emailVerification");

        if (!isPublicRequest && !token) {
            // 如果没有 token，则跳转到登录页面
            Swal.fire({
                title: '未登录',
                text: '请先登录！',
                icon: 'warning',
                confirmButtonText: '确定'
            }).then(() => {
                router.push({
                    name: "Login"
                });
            });
            // 抛出一个错误以中断请求
            // return Promise.reject(new Error("未登录，请先登录！"));
        }

        // 将 JWT 令牌添加到请求头中
        if (token) {
            config.headers['token'] = token;
        }

        return config;
    },
    (error) => {
        // return Promise.reject(error);
        Swal.fire({
            title: '系统提示',
            text: error.message || '发生未知错误',
            icon: 'error',
            confirmButtonText: '确定'
        });
        router.push({
            name: "Login"
        });
    }
);

// 响应拦截器
apiClient.interceptors.response.use(
    (response) => {
        if (response.data.code === 1) {
            return response.data;
        } else if (response.data.code === 0) {
            Swal.fire({
                title: '错误',
                text: response.data.msg,
                icon: 'error',
                confirmButtonText: '确定'
            });
            // return Promise.reject(response.data);
        }
        return response;
    },
    (error) => {
        Swal.fire({
            title: '请求失败',
            text: error.message || '发生未知错误',
            icon: 'error',
            confirmButtonText: '确定'
        });
        // return Promise.reject(error);
    }
);

// 封装 GET 请求
export const get = (url, params = {}) => {
    return apiClient.get(url, {
            params
        })
        .then(response => response)
        .catch(error => {
            Swal.fire({
                title: '请求失败',
                text: error.message || '发生未知错误',
                icon: 'error',
                confirmButtonText: '确定'
            });
        });
};

// 封装 POST 请求
export const post = (url, data) => {
    return apiClient.post(url, data)
        .then(response => response)
        .catch(error => {
            Swal.fire({
                title: '请求失败',
                text: error.message || '发生未知错误',
                icon: 'error',
                confirmButtonText: '确定'
            });
        });
};

// 封装 PUT 请求
export const put = (url, data) => {
    return apiClient.put(url, data)
        .then(response => response)
        .catch(error => {
            Swal.fire({
                title: '请求失败',
                text: error.message || '发生未知错误',
                icon: 'error',
                confirmButtonText: '确定'
            });
        });
};

// 封装 DELETE 请求
export const del = (url) => {
    return apiClient.delete(url)
        .then(response => response)
        .catch(error => {
            Swal.fire({
                title: '请求失败',
                text: error.message || '发生未知错误',
                icon: 'error',
                confirmButtonText: '确定'
            });
        });
};